package com.gzx.plugin.tjzy.feign.file.service.impl;

import com.aliyun.oss.ServiceException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.gzx.plugin.tjzy.feign.file.service.FileFeignService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author zjt
 * @description
 * @date 2024/10/18 15:11
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class FileFeignServiceImpl implements FileFeignService {

    private final AmazonS3 amazonS3;

    @Value("${jd.oss.bucket-name}")
    private String bucketNameA;

    /**
     * 以文件的形式获取文件
     * @param fileName
     * @return
     */
    @Override
    public File getFile(String fileName) {
        File tempFile = null;
        try {
            File file = File.createTempFile( fileName.split("\\.")[0], ".xlsx");
            // 新的文件名，不包含随机部分
            tempFile = new File(file.getParent(), fileName);
            //tempFile = File.createTempFile(fileName.split("\\.")[0], "."+fileName.split("\\.")[1]);
            try (S3Object o = amazonS3.getObject(bucketNameA, fileName);
                 S3ObjectInputStream s3is = o.getObjectContent();
                 BufferedInputStream inputStream = new BufferedInputStream(s3is);
                 FileOutputStream outputStream = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer))!= -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                System.out.println("File downloaded successfully.");
            }
        } catch (AmazonServiceException e) {
            // Amazon S3 服务错误
            log.error("AmazonServiceException occurred: ", e.getErrorCode());
            return null;
        } catch (SdkClientException e) {
            // AWS SDK 客户端错误
            log.error("SdkClientException occurred: ", e.getMessage());
        } catch (IOException e) {
            // 输入输出错误
            log.error("IOException occurred: ", e.getMessage());
        }
        return tempFile;
    }
    /**
     * 上传文件不带有时间后缀
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public String uploadNoTimeSuffix(MultipartFile file) throws IOException {
        //获取输入流
        InputStream inputStream = file.getInputStream();
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpeg");
        objectMetadata.setContentLength(file.getSize());
        String[] parts = file.getOriginalFilename().split("\\.");
        if (parts.length <= 1) {
            throw new ServiceException("文件上传失败");
        }
        String fileName = parts[0] +  "." + parts[1];
        try {
            amazonS3.putObject(bucketNameA, fileName, inputStream, objectMetadata);
            log.info("文件上传成功:{}，to:{}", fileName, bucketNameA);
        } catch (AmazonServiceException e) {
            e.printStackTrace();
        }
        return fileName;
    }
}
